package com.vzhv.myself.controller;

import com.vzhv.myself.mapper.UserMapper;
import com.vzhv.myself.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

   @RequestMapping("/insert")
    public void insert(User user){
       System.out.println("user = " + user);
       mapper.insert(user);
   }

   @RequestMapping("/check")
    public int select(String username){
       User u = mapper.selectByUsername(username);
       return u == null?1:2;//1不存在可以使用    2存在不可以使用
   }

   @RequestMapping("/login")
    public int select(User user, HttpSession session){
       User u = mapper.selectByUsername(user.getUsername());
       if (u != null){
           if (u.getPassword().equals(user.getPassword())){
               //把登录成功的当前对象放入session回话对象中
               session.setAttribute("u",u);//Attribute:把……归因于
               return 1;//登录成功
           }else {
               return 2;//登录失败
           }
       }
       return 3;//用户名不存在
   }

   @RequestMapping("/currentUser")
    public User current(HttpSession session){
       return (User) session.getAttribute("u");
   }

   @RequestMapping("/logout")
    public void logout(HttpSession session){
       session.removeAttribute("u");
   }
}
